""" 

    vcard.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a list of Ids and returns the legislator's information in vCard format.

    Accepts one parameters:
        ids (required) - comma delimited list of Bioguide Ids
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"

import os
import wsgiref.handlers
import const
import facebook
import base64

from datetime import datetime
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
        
from utils import fbUtil, SunlightUtil, memcacheUtil, textUtil

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "text/x-vcard; charset=utf-8"
        legislators = {"legislators": []}
        sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
        
        theIds = self.request.get('id', default_value=None)
            
        if theIds is not None: 
            legislatorIds = theIds.split(",")          
            for legislatorId in legislatorIds:
                legislator = sunlight.apicall("legislators.get", {"bioguide_id": legislatorId})
                if legislator is not None:
                    legislator["legislator"]["friendly_name"] = const.FRIENDLY_NAME[legislatorId]
                    legislators["legislators"].append(legislator["legislator"])      

        path = os.path.join(os.path.dirname(__file__), '../templates/vcard.fbml')     
        self.response.out.write(template.render(path, legislators))
        
        
def main():
    application = webapp.WSGIApplication([('/fb/vcard', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
